#include <queue>
using namespace std;
class Node {
public:
    int val;
    Node* left;
    Node* right;
    Node* next;

    Node() : val(0), left(nullptr), right(nullptr), next(nullptr) {}

    Node(int _val) : val(_val), left(nullptr), right(nullptr), next(nullptr) {}

    Node(int _val, Node* _left, Node* _right, Node* _next)
        : val(_val), left(_left), right(_right), next(_next) {}
};

Node* connect(Node* root) {
    if(!root) return nullptr;
    queue<Node*> q;
    q.push(root);
    Node *last = nullptr;
    while(!q.empty()) {
        int sz = q.size();
        for(int i = 0; i < sz; ++i) {
            Node *f = q.front();
            if(f->left) q.push(f->left);
            if(f->right) q.push(f->right);
            q.pop();
            if(i != 0) {
                last->next = f;
            }
            last = f;
        }
    }
    return root;
}